package com.brush.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.brush.common.constant.CacheConstants;
import com.brush.common.core.domain.entity.SysDictType;
import com.brush.common.core.domain.resp.SysDictDataQueryResp;
import com.brush.common.exception.ServiceException;
import com.brush.common.exception.database.PrimaryKeyException;
import com.brush.common.exception.database.RecordNotFoundException;
import com.brush.common.utils.MessageUtils;
import com.brush.system.domain.req.sysdicttype.SysDictTypeAddReq;
import com.brush.system.domain.req.sysdicttype.SysDictTypeEditReq;
import com.brush.system.domain.req.sysdicttype.SysDictTypeQueryReq;
import com.brush.system.domain.resp.sysdicttype.SysDictTypeQueryResp;
import com.brush.system.mapper.SysDictTypeMapper;
import com.brush.system.service.SysDictDataService;
import com.brush.system.service.SysDictTypeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 18494
 * @description 针对表【sys_dict_type(字典类型表)】的数据库操作Service实现
 * @createDate 2024-08-19 10:28:03
 */
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType>
        implements SysDictTypeService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 字典明细业务逻辑
     */
    @Autowired
    private SysDictDataService sysDictDataService;

    @Override
    public PageInfo<SysDictTypeQueryResp> paginationQuery(SysDictTypeQueryReq req) {
        return PageHelper.startPage(req.getPageNum(), req.getPageSize()).doSelectPageInfo(() -> {
            // 调用sysConfigMapper[mybatis]的分页查询方法, 要么使用lambdaQueryWrapper来写【mybatis-plus】
            // 一定返回的结果是 List<SysConfigResp>
            this.baseMapper.paginationQuery(req);
        });
    }

    /**
     * 程序启动的时候，spring容器会自动的调用这一个@PostConstruct
     */
    @PostConstruct
    public void init() {
        //如果缓存中没有数据，则加载
        String redisKey = CacheConstants.SYS_DICT_KEY + "*";
        Set keys = redisTemplate.keys(redisKey);
        if (keys.isEmpty()) {
            this.loadingDictCache();
        }
    }


    /**
     * 加载字典缓存数据
     */
    @Override
    public void loadingDictCache() {
        // 从数据库中查询所有state='0'数据
        List<SysDictDataQueryResp> allList = this.sysDictDataService.findEnableAll();
        //分组转换 jdk8新特性 分组（像数据库中group by 列）
        Map<String, List<SysDictDataQueryResp>> collect = allList.stream().collect(Collectors.groupingBy(SysDictDataQueryResp::getDictType));

        collect.forEach((key, value) -> {
            // 缓存到redis中
            String redisKey = CacheConstants.SYS_DICT_KEY + key;
            redisTemplate.opsForValue().set(redisKey, value);
        });
    }

    /**
     * 清空字典缓存数据
     */
    @Override
    public void clearDictCache() {
        String redisKey = CacheConstants.SYS_DICT_KEY + "*";
        Set keys = redisTemplate.keys(redisKey);
        this.redisTemplate.delete(keys);

    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache() {
        this.clearDictCache();
        this.loadingDictCache();
    }

    /**
     * 添加字典类型
     *
     * @param req
     * @return
     */
    @Override
    public boolean add(SysDictTypeAddReq req) {
        // 验证字典名称和字典类型是否已经存在
        if (this.baseMapper.exists(new LambdaQueryWrapper<SysDictType>().eq(SysDictType::getDictName, req.getDictName()))) {
            throw new ServiceException(MessageUtils.message("sysdicttype.name.exists"));
        } else if (this.baseMapper.exists(new LambdaQueryWrapper<SysDictType>().eq(SysDictType::getDictType, req.getDictType()))) {
            throw new ServiceException(MessageUtils.message("sysdicttype.type.exists"));
        }

        SysDictType newEntity = new SysDictType();

        BeanUtils.copyProperties(req, newEntity);

        boolean save = this.save(newEntity);
        if (save) {
            // 清空缓存
            redisTemplate.opsForValue().set(CacheConstants.SYS_DICT_KEY + req.getDictType(), newEntity);
        }

        return save;
    }

    @Override
    public SysDictTypeQueryResp findById(Long id) {
        if (Objects.isNull(id)) {
            throw new PrimaryKeyException();
        }

        // 根据主键查询
        SysDictType db = this.getById(id);
        // 数据库找不到数据
        if (Objects.isNull(db)) {
            throw new RecordNotFoundException();
        }

        // 封装成返回对象
        SysDictTypeQueryResp resp = new SysDictTypeQueryResp();
        BeanUtils.copyProperties(db, resp);

        return resp;

    }

    @Override
    public boolean edit(SysDictTypeEditReq req) {
        // 根据主键查询
        SysDictType db = this.getById(req.getDictId());
        // 数据库找不到数据
        if (Objects.isNull(db)) {
            throw new RecordNotFoundException();
        }

        // 验证DictType和DictName是否已经存在
        if (!req.getDictType().equals(db.getDictType()) && !req.getDictName().equals(db.getDictName())) {
            // 判断DictType是否已经被使用
            if (this.baseMapper.exists(new LambdaQueryWrapper<SysDictType>().eq(SysDictType::getDictType, req.getDictType()))) {
                throw new ServiceException(MessageUtils.message("sysdicttype.dicttype.exists"));
            }
            // 判断DictName是否已经被使用
            if (this.baseMapper.exists(new LambdaQueryWrapper<SysDictType>().eq(SysDictType::getDictName, req.getDictName()))) {
                throw new ServiceException(MessageUtils.message("sysdicttype.dictname.exists"));
            }
        }

        // 覆盖数据库对象的值
        BeanUtils.copyProperties(req, db);
        boolean result = this.updateById(db);
        if (result) {
            // 覆盖缓存
            redisTemplate.opsForValue().set(CacheConstants.SYS_CONFIG_KEY + db.getDictType(), db);
        }
        return result;
    }

    @Override
    public void deleteDictTypeByIds(Long[] dictIds) {
        for (Long dictId : dictIds) {
            SysDictType dictType = this.getById(dictId);
            if (this.sysDictDataService.countDictDataByType(dictType.getDictType()) > 0) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
           this.removeById(dictId);
            // 清除缓存
            this.redisTemplate.delete(CacheConstants.SYS_CONFIG_KEY + dictType.getDictType());
        }
    }

    /**
     * 下拉列表选项框
     * @return
     */
    @Override
    public List<SysDictTypeQueryResp> optionSelect() {
        return this.baseMapper.paginationQuery(new SysDictTypeQueryReq());
    }
}




